package com.example.service.impl;

import com.example.entity.Emp;
import com.example.exception.BusinessException;
import com.example.service.EmpService;
import com.example.service.LoginService;
import com.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private EmpService empService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(String username, String password) {
        // 1. 根据用户名查询用户
        Emp emp = empService.getByUsername(username);
        
        // 2. 判断用户是否存在
        if (emp == null) {
            throw new BusinessException("用户名或密码错误");
        }
        
        // 3. 验证密码是否正确
        if (!passwordEncoder.matches(password, emp.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        
        // 4. 生成JWT令牌并返回
        return jwtUtils.createToken(username);
    }
} 